package com.scau.database.service.salesperson;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scau.data.entity.*;
import com.scau.database.common.service.ImportMapperService;
import com.scau.database.entity.salesperson.sell.BuyResultDTO;
import com.scau.database.entity.salesperson.sell.SellVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 给售货员提供service
 */
@Service
public class SellService {
    private static final Integer SUCCESS_BUY = 1; // 购买成功
    private static final Integer LACK =  2; // 缺货
    private static final Float  ZERO_THRESHOLD = new Float("0.01");


    @Autowired
    ImportMapperService importMapperService;
    /**
     * 模拟扫描商品条码获取信息
     * 随机返回本店在售有余量的商品
     * @return
     */
  public SellVO getSell(Integer storeId){
      // 查询shelf_ok中该店铺有余量的行
      // 随机取一行，再从on_sell里查询信息
      QueryWrapper<ShelfOKDO> shelfOKDOQueryWrapper = new QueryWrapper<>();
      shelfOKDOQueryWrapper.eq("store_id",storeId)
              .ge("surplus",1);
      List<ShelfOKDO> shelfOKDOS = importMapperService.shelfOKMapper.selectList(shelfOKDOQueryWrapper);
      if (shelfOKDOS.size() < 1)return null; // 没货可卖
      Random random = new Random();
      int i = random.nextInt(shelfOKDOS.size());
      ShelfOKDO shelfOKDO = shelfOKDOS.get(i); // 随机获取其中一个
      String barCode = shelfOKDO.getBarCode();
      QueryWrapper<OnSellDO> onSellDOQueryWrapper = new QueryWrapper<>();
      onSellDOQueryWrapper.eq("bar_code",barCode)
              .eq("store_id",storeId);
      OnSellDO onSellDO = importMapperService.onsellMapper.selectOne(onSellDOQueryWrapper);
      if (onSellDO == null)return null;
      // 下面开始封装返回对象
      SellVO sellVO = new SellVO();
      sellVO.setBar_code(barCode);
      sellVO.setShelf_id(shelfOKDO.getId());
      sellVO.setCount(1);
      sellVO.setUse_special_price(true);
      sellVO.setOriginal_price(onSellDO.getOriginalPrice());
      sellVO.setSpecial_price(onSellDO.getSpecialPrice());
      if (sellVO.getSpecial_price() != null){
          sellVO.setDeal_price(sellVO.getSpecial_price());
      }else {
          sellVO.setDeal_price(sellVO.getOriginal_price());
      }
      QueryWrapper<CommodityInfoDO> commodityInfoDOQueryWrapper = new QueryWrapper<>();
      commodityInfoDOQueryWrapper.eq("bar_code",barCode);
      CommodityInfoDO commodityInfoDO = importMapperService.commodityInfoMapper.selectOne(commodityInfoDOQueryWrapper);
      sellVO.setName(commodityInfoDO.getName());
      return sellVO;
  }

    /**
     * 根据手动输入的商品坐标信息
     * 返回商品相关信息
     * @param storeId 店铺id
     * @param barCode 商品码
     * @param shelfId 上架流水号
     * @return
     */
  public SellVO getSell(Integer storeId,String barCode,Long shelfId){
      // 查询shelf_ok表，查看余量是否充足
      // 查找onsell表得到该店销售信息
      // 封装返回对象
      QueryWrapper<ShelfOKDO> shelfOKDOQueryWrapper = new QueryWrapper<>();
      shelfOKDOQueryWrapper.eq("store_id",storeId)
              .eq("bar_code",barCode)
              .eq("id",shelfId);
      ShelfOKDO shelfOKDO = importMapperService.shelfOKMapper.selectOne(shelfOKDOQueryWrapper);

        QueryWrapper<OnSellDO> onSellDOQueryWrapper = new QueryWrapper<>();
        onSellDOQueryWrapper.eq("store_id",storeId)
                .eq("bar_code",barCode);
        OnSellDO onSellDO = importMapperService.onsellMapper.selectOne(onSellDOQueryWrapper);
        if (onSellDO == null || shelfOKDO == null)return null; // 如果不存在，返回空
        if (onSellDO.getSurplus() < 1 || shelfOKDO.getSurplus() < 1)return null; // 库存不足


        // 封装返回对象
        SellVO sellVO = new SellVO();
        sellVO.setBar_code(barCode);
        sellVO.setCount(1);
        sellVO.setShelf_id(shelfId);
        sellVO.setSpecial_price(onSellDO.getSpecialPrice());
        QueryWrapper<CommodityInfoDO> commodityInfoDOQueryWrapper = new QueryWrapper<>();
        commodityInfoDOQueryWrapper.eq("bar_code",barCode);
        CommodityInfoDO commodityInfoDO = importMapperService.commodityInfoMapper.selectOne(commodityInfoDOQueryWrapper);
        sellVO.setName(commodityInfoDO.getName());
        sellVO.setOriginal_price(onSellDO.getOriginalPrice());
        sellVO.setUse_special_price(true); // 没有会员系统，默认使用特价
        if (sellVO.getSpecial_price() != null){
            sellVO.setDeal_price(sellVO.getSpecial_price());
        }else {
            sellVO.setDeal_price(sellVO.getOriginal_price());
        }



      return sellVO;
  }

    /**
     * 处理购买订单
     * @param storeId 店铺ID
     * @param sellVOS 购买商品列表
     * @return
     */
    @Transactional
  public BuyResultDTO buy(Integer storeId, List<SellVO> sellVOS){
        // 查询是否有库存（on_sell , shelf_ok）
        // 检查限购 commodity_info
        // 修改库存
        // 构建shopDO, 与相对应的shopLineDD们
        // 保存
        BuyResultDTO buyResultDTO = new BuyResultDTO();
        buyResultDTO.setStatus(SUCCESS_BUY); // 默认购买成功
        buyResultDTO.setLackIndexs(new ArrayList<Integer>());
        buyResultDTO.setLimitBuy(new HashMap<Integer, Integer>());
        buyResultDTO.setCountError(new ArrayList<Integer>());
        buyResultDTO.setPriceError(new ArrayList<Integer>());
        List<ShopLineDO> shopLineDOS = new ArrayList<>(); // shop_line
        BigDecimal totalPrice = BigDecimal.ZERO;



        Iterator<SellVO> iterator = sellVOS.iterator();
        while (iterator.hasNext()){
            SellVO next = iterator.next();
            String barCode = next.getBar_code();
            // 检查库存
            QueryWrapper<OnSellDO> onSellDOQueryWrapper = new QueryWrapper<>();
            onSellDOQueryWrapper.eq("store_id",storeId)
                    .eq("bar_code",barCode);
            OnSellDO onSellDO = importMapperService.onsellMapper.selectOne(onSellDOQueryWrapper);

            QueryWrapper<ShelfOKDO> shelfOKDOQueryWrapper = new QueryWrapper<>();
            shelfOKDOQueryWrapper.eq("store_id",storeId)
                    .eq("bar_code",barCode)
                    .eq("id",next.getShelf_id());
            ShelfOKDO shelfOKDO = importMapperService.shelfOKMapper.selectOne(shelfOKDOQueryWrapper);

            // 判断库存
            if (    next.getCount() == null ||
                    shelfOKDO == null ||
                    onSellDO == null ||
                    next.getCount() > shelfOKDO.getSurplus() ||
                    next.getCount() > onSellDO.getSurplus()  ){
                buyResultDTO.setStatus(LACK); // 设置缺货
                buyResultDTO.getLackIndexs().add(next.getIndex()); // 将缺货索引记录
                continue; // 下一个
            }

            // 检查限购
            QueryWrapper<CommodityInfoDO> commodityInfoDOQueryWrapper = new QueryWrapper<>();
            commodityInfoDOQueryWrapper.eq("bar_code",barCode);
            CommodityInfoDO commodityInfoDO = importMapperService.commodityInfoMapper.selectOne(commodityInfoDOQueryWrapper);
            Integer limitBuy = commodityInfoDO.getLimitBuy();
            if (limitBuy != null && limitBuy > 0){
                // 有限购条款
                if (next.getCount() > limitBuy){
                    buyResultDTO.setStatus(LACK);
                    buyResultDTO.getLimitBuy().put(next.getIndex(),limitBuy); // 限购信息
                    continue;
                }
            }

            // 检查count
            if (next.getCount() == null || next.getCount() <= 0){
                buyResultDTO.setStatus(LACK);
                buyResultDTO.getCountError().add(next.getIndex());
                continue;
            }
            // 检查价格
            BigDecimal originalPrice = onSellDO.getOriginalPrice();
            BigDecimal specialPrice = onSellDO.getSpecialPrice();
            if (Math.abs(originalPrice.floatValue() - next.getOriginal_price().floatValue()) > ZERO_THRESHOLD ||
            specialPrice != null && Math.abs(specialPrice.floatValue() - next.getSpecial_price().floatValue()) > ZERO_THRESHOLD ||
            specialPrice == null && next.getSpecial_price() != null ||
            specialPrice != null && next.getSpecial_price() == null){
                buyResultDTO.setStatus(LACK);
                buyResultDTO.getPriceError().add(next.getIndex());
                continue;
            }


            // 修改库存
            importMapperService.shelfOKMapper.reduceSurplusById(next.getShelf_id(),next.getCount());
            importMapperService.onsellMapper.reduceSurplus(storeId,barCode,next.getCount());

            // 封装shop_line

            ShopLineDO shopLineDO = new ShopLineDO();
//            shopLineDO.setShopId(shopId);
            shopLineDO.setIndex(next.getIndex());
            shopLineDO.setBarCode(next.getBar_code());
            shopLineDO.setShelfId(next.getShelf_id());
            shopLineDO.setCount(next.getCount());

            shopLineDO.setDealPrice(next.getDeal_price());
            shopLineDO.setOriginalPrice(next.getOriginal_price());
            shopLineDO.setSpecialPrice(next.getSpecial_price());

            shopLineDO.setUseSpecialPrice(next.getUse_special_price());

            shopLineDOS.add(shopLineDO);
            // 总价计算
            totalPrice = totalPrice.add(next.getDeal_price().multiply(new BigDecimal(next.getCount())));

        }//while end

        // 如果有缺货、限购、数据异常
        if (buyResultDTO.getStatus().equals(LACK)){
            return buyResultDTO;
        }


        // 封装shop对象
        ShopDO shopDO = new ShopDO();
        shopDO.setStoreId(storeId);
        shopDO.setTime(new Date());
        importMapperService.shopMapper.insert(shopDO);
        Long shopId = shopDO.getId();

        // 给shop_line赋值
        shopLineDOS.forEach(shopLineDO -> shopLineDO.setShopId(shopId));

        // 更新总价
        shopDO.setTotalPrice(totalPrice);
        QueryWrapper<ShopDO> shopDOQueryWrapper = new QueryWrapper<>();
        shopDOQueryWrapper.eq("id",shopDO.getId());
        int update = importMapperService.shopMapper.update(shopDO, shopDOQueryWrapper);

        // 将shop_line持久化
        shopLineDOS.forEach(shopLineDO -> importMapperService.shopLineMapper.insert(shopLineDO));


        return buyResultDTO;
    }
}
